package com.nuoniu.sibanyun.filter;

import com.alibaba.fastjson.JSONObject;
import com.nuoniu.sibanyun.authException.AccountErrorException;
import com.nuoniu.sibanyun.authException.RefreshVerifyCodeException;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.common.result.HttpResult;
import com.nuoniu.sibanyun.common.result.ResultStatusCode;
import com.nuoniu.sibanyun.common.web.http.UserAgentUtils;
import com.nuoniu.sibanyun.config.JwtUser;
import com.nuoniu.sibanyun.config.JwtUtils;
import com.nuoniu.sibanyun.config.SpringContextHolder;
import com.nuoniu.sibanyun.entity.SysUser;
import com.nuoniu.sibanyun.entity.dto.LoginDto;
import com.nuoniu.sibanyun.service.RSA.RsaService;
import com.nuoniu.sibanyun.service.impl.SysLogServiceImpl;
import com.nuoniu.sibanyun.service.impl.SysUserServiceImpl;
import com.nuoniu.sibanyun.service.redis.RedisService;
import com.nuoniu.sibanyun.utils.IpUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证用户名密码正确后，生成一个token，并将token返回给客户端
 * 该类继承自UsernamePasswordAuthenticationFilter，重写了其中的2个方法 ,
 * attemptAuthentication：接收并解析用户凭证。
 * successfulAuthentication：用户成功登录后，这个方法会被调用，我们在这个方法里生成token并返回。
 */
@Log4j2
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    private final static String ERROR_NUMBER  = "ERROR_NUMBER";

    //ERROR_NUMBER_TIME 时间段内 允许连续最大错误次数
    private final static Integer MAX_ERROR_NUMBER  = 2;
    //错误次数 redis 存放时间
    private final static Integer ERROR_NUMBER_TIME  = 60 * 30;  //秒

    private AuthenticationManager authenticationManager;

    private  JwtUtils jwtUtils =  SpringContextHolder.getBean(JwtUtils.class);

    private RedisService redisService =  SpringContextHolder.getBean(RedisService.class);

    private RsaService rsaService =  SpringContextHolder.getBean(RsaService.class);

    private SysLogServiceImpl logService =  SpringContextHolder.getBean(SysLogServiceImpl.class);

    private SysUserServiceImpl userService = SpringContextHolder.getBean(SysUserServiceImpl.class);

    public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
        super.setFilterProcessesUrl("/auth/login");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        // 从输入流中获取到登录的信息
        try {
            LoginDto loginUser = JSONObject.parseObject(request.getInputStream(), LoginDto.class);
            System.out.println("用户名：" +loginUser.getUserName());
            String userName = rsaService.decrypt(loginUser.getUserName());
            SysUser user = userService.findByUserName(userName);
            if(user != null && user.getStatus() != null && user.getStatus().equals(3)) {
                throw new DisabledException("账户被停用，请联系管理员");
            }

            String password = rsaService.decrypt(loginUser.getPassword());
            //是否需要验证 图片验证码
            String ip = IpUtil.getClientIp(request);
//            if(StringUtils.isNoneBlank(ip)){
//                Object o = redisService.get(ip + ERROR_NUMBER);
//                if(null != o && o instanceof Integer){
//                    Integer errorNumber = (Integer) o;
//                    if(errorNumber > MAX_ERROR_NUMBER ){
//                        if(StringUtils.isBlank(loginUser.getVerifyCode())){
//                            throw new AccountErrorException("请输入验证码");
//                        }else {
//                            Object verifyCodeObj = redisService.get("login_"+ userName + "_" + ip);
//                            if(null != verifyCodeObj && verifyCodeObj instanceof String){
//                                String verifyCode = (String)verifyCodeObj;
//                                if(!verifyCode.toLowerCase().equals(loginUser.getVerifyCode().toLowerCase())){
//                                    redisService.del("login_"+ userName + "_"+ ip);
//                                    throw new RefreshVerifyCodeException("验证码错误") ;
//                                }
//                            }else{
//                                throw new RefreshVerifyCodeException("验证码错误") ;
//                            }
//                        }
//                    }
//                }
//            }

            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(userName, password)
            );
        } catch (IOException e) {
            throw new NuoNiuException("登录异常,请刷新网页重试");
        }
    }

    // 成功验证后调用的方法
    // 如果验证成功，就生成token并返回
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {
        //清除 登录错误次数
        String ip = IpUtil.getClientIp(request);
        if(StringUtils.isNotBlank(ip)){
            redisService.del(ip + ERROR_NUMBER);
        }
        long time = System.currentTimeMillis();
        //判断 请求是否来自移动端
        boolean isMobile = UserAgentUtils.checkAgentIsMobile(request.getHeader("User-Agent"));
        JwtUser jwtUser = (JwtUser) authResult.getPrincipal();
        String username = jwtUser.getUsername();
        log.info("登录ip:{},用户：{}，登录成功,并准备创建Token",ip,username);
        String token = jwtUtils.createToken(username,isMobile);
        //String token = JwtTokenUtils.createToken(jwtUser.getUsername(), false);
        // 返回创建成功的token
        // 但是这里创建的token只是单纯的token
        // 按照jwt的规定，最后请求的时候应该是 `Bearer token`

        //生成新token时，初始化token到Redis
        jwtUtils.initNewToken(username,token,isMobile,true);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Expose-Headers", JwtUtils.TOKEN_HEADER);
        String tokenStr = JwtUtils.TOKEN_PREFIX + token;
        response.setHeader(JwtUtils.TOKEN_HEADER,tokenStr);
        //更新用户登录信息
        userService.updateLoginInfo(jwtUser.getId());
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        HttpResult httpResult;
        if (failed instanceof BadCredentialsException ||
                failed instanceof UsernameNotFoundException) {
            String errorMessage = "";
            boolean notFound = failed instanceof UsernameNotFoundException;
            if (notFound){
                errorMessage = "用户不存在";
            }
            //设置错误次数
            String ip = IpUtil.getClientIp(request);
            Object o = redisService.get(ip + ERROR_NUMBER);
            if(null != o ){
                Integer errors = 1;
                if(o instanceof Integer) {
                    Integer errorNumber = (Integer) o;
                    errors = errorNumber + 1;
                }
                redisService.set(ip + ERROR_NUMBER , errors );
                if(errors > MAX_ERROR_NUMBER ){
                    httpResult = HttpResult.error(ResultStatusCode.USER_NEED_CHECK_VERIFY_CODE,errorMessage);
                }else {
                    httpResult = HttpResult.error(ResultStatusCode.USER_ACCOUNT_OR_PWD_ERROR,errorMessage);
                }
            }else{
                redisService.set(ip + ERROR_NUMBER , 1 ,ERROR_NUMBER_TIME);
                httpResult = HttpResult.error(ResultStatusCode.USER_ACCOUNT_OR_PWD_ERROR,errorMessage);
            }
        } else if (failed instanceof LockedException) {
            httpResult = HttpResult.error(ResultStatusCode.USER_ACCOUNT_LOCKED);
        } else if (failed instanceof CredentialsExpiredException) {
            httpResult = HttpResult.error(ResultStatusCode.USER_PWD_EXPIRED);
        } else if (failed instanceof AccountExpiredException) {
            httpResult = HttpResult.error(ResultStatusCode.USER_ACCOUNT_EXPIRED);
        } else if (failed instanceof DisabledException) {
            httpResult = HttpResult.error(ResultStatusCode.USER_ACCOUNT_DISABLED);
        } else if (failed instanceof AccountErrorException) {
            httpResult = HttpResult.error(ResultStatusCode.USER_NEED_CHECK_VERIFY_CODE.getCode(),failed.getMessage());
        }else if (failed instanceof RefreshVerifyCodeException) {
            httpResult = HttpResult.error(ResultStatusCode.USER_NEED_REFRESH_VERIFY_CODE.getCode(),failed.getMessage());
        }  else {
            httpResult = HttpResult.error(ResultStatusCode.USER_UNAUTHO_FIAL);
        }
        response.setStatus(401);
        response.getWriter().print(JSONObject.toJSONString(httpResult));
    }
}

